package com.wx.rpc.client.core;

import com.wx.rpc.service.request.RPCRequest;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author wx
 * @Description:
 * @date 2019/3/9 000915:34
 */
public class RPCTransPort {

    private String serviceAddress;

    public RPCTransPort(String serviceAddress) {
        this.serviceAddress = serviceAddress;
    }

    /**
     * @description: 发送请求
     * @author: wx
     * @date: 2019/3/9 0009
     * @param request
     * @return: java.lang.Object
     */
    public Object send(RPCRequest request) {
        Socket socket = null;
        try {
            // 输出服务请求参数到服务端代码======================
            socket = newSocket();
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(request);
            outputStream.flush();

            // 服务端响应结果代码=========================
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            Object result = inputStream.readObject();
            inputStream.close();
            outputStream.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @description: 获取Socket
     * @author: wx
     * @date: 2019/3/9 0009
     * @param
     * @return: java.net.Socket
     */
    private Socket newSocket() {
        Socket socket = null;
        try {
            String[] addressArr = serviceAddress.split(":", -1);
            socket = new Socket(addressArr[0], Integer.valueOf(addressArr[1]));
            return socket;
        } catch (Exception e) {
            throw new RuntimeException("CREATED CONNECTION FAILED=======");
        } finally {
        }
    }


}
